//
//  MainViewController.m
//  Daybook
//
//  Created by dllo on 16/5/18.
//  Copyright © 2016年 zhangbin. All rights reserved.
//

#import "MainViewController.h"
#import "Common.h"
#import "UpdateViewController.h"
#import "AccountBookHearderView.h"
#import "CellEditState.h"
#import "MainDetailViewController.h"
#import <BmobSDK/Bmob.h>
#import "LoginViewController.h"

@interface MainViewController ()
<
     MainViewDelegate,
     RightViewDelegate,
    UITableViewDataSource,
    UITableViewDelegate,
    RightCellDeleteDelegate,
    LeftCellDeleteDelegate,
    LeftViewDelegate,
    LeftAddViewControllerDelegate
>

@property (nonatomic, strong) MainView *mainView;
@property (nonatomic, strong) RightView *rightView;

@property (nonatomic, strong) UIButton *leftButton;

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSMutableArray *accountBookArr;

@property (nonatomic, strong)UIView *lineView;

@property (nonatomic, strong)RLMRealm *realm;

@property (nonatomic, strong)RLMResults *accountBooks;

@property (nonatomic, strong)NSMutableArray *countArr;

@property (nonatomic, strong)NSNumber *sumMoney;

@property (nonatomic, strong)NSMutableArray *dayCountArr;

@property (nonatomic, strong)NSMutableArray *moneyArr;


@property (nonatomic, strong)NSMutableArray *accountBooksArr;

@property (nonatomic, strong)CellEditState *cellEditState;

//
@property (nonatomic, strong) LeftView *leftView;


@property (nonatomic, strong) UIView *headView;


@property (nonatomic, assign) BOOL isclick;

@property (nonatomic, strong) AccountBookModel *model;

@property (nonatomic, assign) BOOL isEdit;

@property (nonatomic, strong)AccountBookHearderView *accountBookHearderView;

@property (nonatomic, strong) NSMutableArray *modelArray;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, assign) NSInteger index;

@property (nonatomic, strong) UIView *sliderView;

@end
@implementation MainViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    
    self.isEdit = NO;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"rightViewExchangeAccountBook" object:nil];

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    self.index = [user integerForKey:@"index"];
    


    
    _leftView.index = self.index;
    self.modelArray = [[AccountBookSQL shareDataBaseTool] select];
    _leftView.modelArray = self.modelArray;
    
    self.model = _modelArray[_index];
    [self.mainView.topMiddleButton setTitle:_model.accountBookName forState:UIControlStateNormal];
    self.mainView.topImageView.image = [UIImage imageNamed:_model.accountBookBackground];
    
    self.accountBooks = [Account allObjects];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"editChanged" object:nil];
    
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"leftCellEditChanged" object:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"moneyChanged" object:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"incomeChanged" object:nil];
    
    [self createData];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;

}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self createDefaultBook];
    [self createView];
    [self createData];
    
//    // 改变状态栏前景色为白色
//    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
//    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    
}

- (void)createDefaultBook {
#pragma mark - 创建默认账本
    NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"沙盒路径%@",sandBox);
    
    NSUserDefaults *accountBookIndex = [NSUserDefaults standardUserDefaults];
    NSInteger numIndex = [accountBookIndex integerForKey:@"index"];
    
    if (numIndex == 0) {
        NSUserDefaults *bookIndex = [NSUserDefaults standardUserDefaults];
        [bookIndex setValue:@"0" forKey:@"accountBookIndex"];
        [RealmTool createDayBookInRealmFromIndex:@"0" name:@"默认账本"];
        
    }
}

- (void)createView {
    [RealmTool getCurrentAccountFromUserDefaults];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    
    self.isEdit = NO;
    _leftView.isEdit = self.isEdit;
    self.isclick = NO;
    if ([[AccountBookSQL shareDataBaseTool] select].count == 0) {
        AccountBookModel *model = [[AccountBookModel alloc] init];
        model.accountBookName = @"默认账本";
        model.accountBookCover = @"AccountBookCover1.png";
        model.accountBookBackground = @"jiandian.jpg";
        [[AccountBookSQL shareDataBaseTool] insertModel:model];
    }
    
    self.leftView = [[LeftView alloc] initWithFrame:CGRectMake(0, 20, MAIN_WIDTH, MAIN_HEIGHT)];
    [self.view addSubview:_leftView];
    
    _leftView.delegate = self;
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT)];
    [self.view addSubview:_headView];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.backgroundScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT)];
    [self.headView addSubview:_backgroundScrollView];
    self.backgroundScrollView.contentSize = CGSizeMake(MAIN_WIDTH * 2, MAIN_HEIGHT);
    self.backgroundScrollView.contentOffset = CGPointMake(0, 0);
    self.backgroundScrollView.bounces = NO;
    self.backgroundScrollView.pagingEnabled = YES;
    
    self.mainView = [[MainView alloc] initWithFrame:CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT)];
    self.mainView.delegate = self;
    [self.backgroundScrollView addSubview:_mainView];
    
    self.rightView = [[RightView alloc] initWithFrame:CGRectMake(MAIN_WIDTH, 0, MAIN_WIDTH, MAIN_HEIGHT)];
    self.rightView.delegate = self;
    [self.backgroundScrollView addSubview:_rightView];
    
    //时间轴
    self.lineView = [[UIView alloc]initWithFrame:CGRectMake(MAIN_WIDTH / 2, MAIN_HEIGHT / 3 + 20 + ((95 / 414.0 * MAIN_WIDTH) / 2), 1, 1)];
    self.lineView.backgroundColor = [UIColor lightGrayColor];
    [self.mainView addSubview:self.lineView];
    
    
    
    
    
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, MAIN_HEIGHT / 3 + 20 + ((95 / 414.0 * MAIN_WIDTH) / 2), MAIN_WIDTH, MAIN_HEIGHT - (MAIN_HEIGHT / 3 + 20 + ((95 / 414.0 * MAIN_WIDTH) / 2))) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.mainView addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 60;
    self.tableView.sectionFooterHeight = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[RightCell class] forCellReuseIdentifier:NSStringFromClass([RightCell class])];
    
    [self.tableView registerClass:[LeftCell class] forCellReuseIdentifier:NSStringFromClass([LeftCell class])];
    
    UIView *tableViewHeaderView = [[UIView alloc]init];
    tableViewHeaderView.backgroundColor =[UIColor clearColor];
    tableViewHeaderView.frame = CGRectMake(0, 0.1, MAIN_WIDTH, 0.1);
    
    self.tableView.tableHeaderView = tableViewHeaderView;
    
    
    self.cellEditState = [CellEditState defaultEdit];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dayMoneyChanged:) name:@"dayMoneyChanged" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exchangeAccountBook:) name:@"exchangeAccountBook" object:nil];

}

- (NSDate *)extractDate:(NSDate *)date {
    //get seconds since 1970
    NSTimeInterval interval = [date timeIntervalSince1970];
    int daySeconds = 24 * 60 * 60;
    //calculate integer type of days
    NSInteger allDays = interval / daySeconds;
    
    return [NSDate dateWithTimeIntervalSince1970:allDays * daySeconds];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dayCountArr.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"时间";
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}


#warning ZoneTitle
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    self.accountBookHearderView = [[AccountBookHearderView alloc]initWithFrame:CGRectMake(0, 0, MAIN_WIDTH, 20)];
    self.accountBookHearderView.moneyLabel.text = [NSString stringWithFormat:@"%.2lf", [self.moneyArr[section] floatValue]];
    self.accountBookHearderView.dateLabel.text = [NSString stringWithFormat:@"%@日", [[NSString stringWithFormat:@"%@", self.dayCountArr[self.dayCountArr.count - 1-  section]] substringWithRange:NSMakeRange(8, 2)]];
    return self.accountBookHearderView;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    RLMResults *result = self.accountBooksArr[section];
    return result.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RLMResults *result = self.accountBooksArr[ indexPath.section];
    Account *accountBook = result[result.count - 1 - indexPath.row];
    
    
    if ([accountBook.type isEqualToString:@"1"]) {
        
        LeftCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LeftCell class]) forIndexPath:indexPath];
        
        
        
        cell.deleteDelegate = self;
        cell.accountBook = accountBook;
        cell.section = indexPath.section;
        cell.index = indexPath.row;
        
        
        return cell;
        
    }
    else {
        
        RightCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([RightCell class]) forIndexPath:indexPath];
        
        
        cell.deleteDelegate = self;
        cell.accountBook = accountBook;
        cell.index = indexPath.row;
        cell.section = indexPath.section;
        return cell;
        
    }
    
    
    
}
#warning createData
- (void)createData {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    RLMResults *result = [RealmTool getCurrentAccountFromUserDefaults];
    DayBook *currentDayBook = [result firstObject];
    
    RLMResults *timeInAccountBooks = (RLMResults *)currentDayBook.bookContent;
    NSMutableArray *timeArr= [timeInAccountBooks valueForKey:@"time"];
//    NSLog(@"%@", timeArr);
    NSMutableArray *dayArr = [NSMutableArray array];
    for (NSInteger i = 0; i < timeArr.count; i ++) {
        NSDate *date = [self extractDate:timeArr[i]];
        [dayArr addObject:date];
    }
//    NSLog(@"%@",dayArr);
    
    
    NSMutableSet *set = [NSMutableSet set];
    self.dayCountArr = [NSMutableArray array];
    for (NSInteger i = dayArr.count - 1; i >=0; i--) {
        [set addObject:dayArr[i]];
    }
//    NSLog(@"1111%@", set);
    
    for (NSDate *date in set) {
        [self.dayCountArr addObject:date];
    }
//    NSLog(@"111%@", self.dayCountArr);
    
    [self.dayCountArr sortUsingSelector:@selector(compare:)];
//    NSLog(@"是不是你%@", self.dayCountArr);
    
    
    
    
//    RLMRealm *realm = [RLMRealm defaultRealm];
    
    //    NSDate *date = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@", self.dayCountArr[0]]];
    //    NSLog(@"%@", [NSString stringWithFormat:@"%@", self.dayCountArr[0]]);
    //    NSDate *date1 = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@", self.dayCountArr[1]]];
    
    
    
    
    
    
    self.moneyArr = [NSMutableArray array];
    self.accountBooksArr = [NSMutableArray array];
    for (NSInteger i = self.dayCountArr.count - 1; i >= 0; i--) {
        NSDate *nextDate = [NSDate dateWithTimeInterval: 24*60*60 sinceDate:self.dayCountArr[i]];
        
        self.accountBooks = [currentDayBook.bookContent objectsWhere:@"time >=  %@ AND time < %@ ", self.dayCountArr[i], nextDate];
        
//        self.accountBooks = [AccountBook objectsInRealm:realm where:@"time >=  %@ AND time < %@ ", self.dayCountArr[i], nextDate];
        RLMResults *accountBooksTypeTwo = [currentDayBook.bookContent objectsWhere:@"time >=  %@ AND time < %@ AND type = '2'", self.dayCountArr[i], nextDate];
        
//        RLMResults *accountBooksTypeTwo = [AccountBook objectsInRealm:realm where:@"time >=  %@ AND time < %@ AND type = '2'", self.dayCountArr[i], nextDate];
        
        [self.accountBooksArr addObject:self.accountBooks];
        
        self.sumMoney = [accountBooksTypeTwo sumOfProperty:@"money"];
        [self.moneyArr addObject:self.sumMoney];
    }
    
//    NSLog(@"%@", self.moneyArr);
    
    
    [self.tableView reloadData];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.y < 0 && self.accountBooks.count > 0) {
        self.lineView.frame = CGRectMake(MAIN_WIDTH / 2, MAIN_HEIGHT / 3 + 20 + ((95 / 414.0 * MAIN_WIDTH) / 2), 1, - scrollView.contentOffset.y);
    }
    
    self.cellEditState.isEdit = NO;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"editChanged" object:nil];
    
}
#warning tableViewdidSelect
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"所在区%ld", indexPath.section);
//    NSLog(@"所在行%ld", indexPath.row);
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    MainDetailViewController *mainDetailVC = [[MainDetailViewController alloc]init];
    
    
    
    
    
    NSInteger count = 0;
    for (NSInteger i = 0; i < indexPath.section; i++) {
        RLMResults *result = self.accountBooksArr[i];
        count =count + result.count;
    }
//    NSLog(@"%ld", count);
    
    mainDetailVC.index = indexPath.row;
    mainDetailVC.count = count;
    [self.navigationController pushViewController:mainDetailVC animated:YES];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"editChanged" object:nil];
}



- (void)rightCellDeleateCell:(NSInteger)index section:(NSInteger)section{
    
    //AccountBook *accountBook = self.accountBooks[self.accountBooks.count - 1- index];
//    NSLog(@"删除了下标%ld",index);
    
    
    RLMResults *result = self.accountBooksArr[section];
    Account *accountBook = result[result.count - 1 - index];
    //    NSLog(@"之前%ld",self.accountBooks.count);
    //    NSLog(@"之前%ld",index);
    //    NSLog(@"之前%ld", self.accountBooks.count -  index);
    
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    [realm deleteObject:accountBook];
    [realm commitWriteTransaction];
    
    [self.tableView reloadData];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"editChanged" object:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"moneyChanged" object:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"dayMoneyChanged" object:nil userInfo:@{@"section": [NSString stringWithFormat:@"%ld", section]}];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"rightViewExchangeAccountBook" object:nil];

    
}

- (void)leftCellDeleateCell:(NSInteger)index section:(NSInteger)section{
    
    
    RLMResults *result = self.accountBooksArr[section];
    Account *accountBook = result[result.count - 1 - index];
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    [realm deleteObject:accountBook];
    [realm commitWriteTransaction];
    
    [self.tableView reloadData];
    
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"leftCellEditChanged" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"editChanged" object:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"incomeChanged" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"rightViewExchangeAccountBook" object:nil];

    
}

- (void)rightEditCell:(NSString *)money pic:(NSString *)pic type:(NSString *)type  remarks:(NSString *)remarks image:(UIImage *)image index:(NSInteger)index section:(NSInteger)section {
    UpdateViewController *updateVC = [[UpdateViewController alloc] init];
    CATransition *backPageAnimation = [CATransition animation];
    backPageAnimation.duration = 0.5;
    backPageAnimation.type = kCATransitionMoveIn;
    backPageAnimation.subtype = kCATransitionFromBottom;
    
    [self.navigationController.view.layer addAnimation:backPageAnimation forKey:nil];
    
    RLMResults *result = self.accountBooksArr[section];
    Account *accountBook = result[result.count - 1 - index];
    
    updateVC.str = [NSMutableString stringWithFormat:@"%@", money];
    updateVC.picName = pic;
    updateVC.time =accountBook.time;
    updateVC.type = type;
    
    updateVC.remarks = remarks;
    updateVC.image = image;
    
    
    [updateVC.addView.picImageView setImage:[UIImage imageNamed:pic]];
    [self.navigationController pushViewController:updateVC animated:NO];
}

- (void)leftEditCell:(NSString *)money pic:(NSString *)pic type:(NSString *)type index:(NSInteger)index {
    
    UpdateViewController *updateVC = [[UpdateViewController alloc] init];
    CATransition *backPageAnimation = [CATransition animation];
    backPageAnimation.duration = 0.5;
    backPageAnimation.type = kCATransitionMoveIn;
    backPageAnimation.subtype = kCATransitionFromBottom;
    
    [self.navigationController.view.layer addAnimation:backPageAnimation forKey:nil];
    
    Account *accountBook = self.accountBooks[self.accountBooks.count - 1 -index];
    
    updateVC.str = [NSMutableString stringWithFormat:@"%@", money];
    updateVC.picName = pic;
    updateVC.time =accountBook.time;
    updateVC.type =type;
    [updateVC.addView.picImageView setImage:[UIImage imageNamed:pic]];
    [self.navigationController pushViewController:updateVC animated:NO];
    
    
}

- (void)dayMoneyChanged:(NSNotification *)notification {
    [self createData];
}

- (void)topLeftButtonAction {
    self.sliderView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, MAIN_WIDTH, MAIN_HEIGHT)];
    _sliderView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    _sliderView.userInteractionEnabled = YES;
    [_headView addSubview:_sliderView];
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe)];
    [swipe setDirection:UISwipeGestureRecognizerDirectionLeft];
    [_sliderView addGestureRecognizer:swipe];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    [_sliderView addGestureRecognizer:tap];
    
    if (self.isclick == NO) {
        [UIView animateWithDuration:0.5 animations:^{
            _sliderView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
            _headView.frame = CGRectMake(MAIN_WIDTH - 100 / 414.0 * MAIN_WIDTH, 0, MAIN_WIDTH, MAIN_HEIGHT);
            
            self.backgroundScrollView.contentSize = CGSizeMake(MAIN_WIDTH, MAIN_HEIGHT);
        } completion:^(BOOL finished) {
            
            
        }];
        
        
    }
    
    
}
- (void)tap {
    [UIView animateWithDuration:0.5 animations:^{
        _sliderView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
        _headView.frame = CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT);
        self.backgroundScrollView.contentSize = CGSizeMake(MAIN_WIDTH * 2, MAIN_HEIGHT);
    } completion:^(BOOL finished) {
        [_sliderView removeFromSuperview];
        
    }];
    self.isclick = NO;
}

- (void)swipe {
    [UIView animateWithDuration:0.5 animations:^{
        _sliderView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
        _headView.frame = CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT);
        self.backgroundScrollView.contentSize = CGSizeMake(MAIN_WIDTH * 2, MAIN_HEIGHT);
    } completion:^(BOOL finished) {
        [_sliderView removeFromSuperview];
        
    }];
    self.isclick = NO;
}

- (void)topRightButtonAction {
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)addButtonAction {
    AddViewController *addVC = [[AddViewController alloc] init];

    
    

    [UIView animateWithDuration:0.6 animations:^{
        _mainView.addButton.transform = CGAffineTransformMakeRotation(M_PI / 2);
    } completion:^(BOOL finished) {
        CATransition *backPageAnimation = [CATransition animation];
        backPageAnimation.duration = 0.5;
        backPageAnimation.type = kCATransitionMoveIn;
        backPageAnimation.subtype = kCATransitionFromBottom;
        
        [self.navigationController.view.layer addAnimation:backPageAnimation forKey:nil];
        
        [self.navigationController pushViewController:addVC animated:NO];
        _mainView.addButton.transform = CGAffineTransformMakeRotation(0);

    }];


    
}
//点击头像
- (void)headLoginAction {
    
    
    BmobUser *bUser = [BmobUser getCurrentObject];
    if (bUser) {
        //进行操作
        MyViewController *myView = [[MyViewController alloc] init];
        
        [self presentViewController:myView animated:YES completion:^{
            
            
        }];
//        CATransition *backPageAnimation = [CATransition animation];
//        backPageAnimation.duration = 0.4;
//        backPageAnimation.type = kCATransitionMoveIn;
//        backPageAnimation.subtype = kCATransitionFromTop;
//        
//        [self.navigationController.view.layer addAnimation:backPageAnimation forKey:nil];

//        CATransition *animation = [Core animationInit];
//        [animation setSubtype:kCATransitionFromTop];
//        [self.navigationController pushViewController:VC animated:NO];//必须设置为no，动画才有效
//        [self.navigationController.view.layer addAnimation:animation forKey:nil];
//        [self.navigationController pushViewController:myView animated:NO];
        
    }else{
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        [self presentViewController:loginVC animated:YES completion:^{
            
            
        }];
        
    }

    
}
//点击添加
- (void)addAction {
    LeftAddViewController *leftAddVC = [[LeftAddViewController alloc] init];
    
    leftAddVC.delegate = self;
    [self presentViewController:leftAddVC animated:YES completion:^{
        
        
    }];
}

- (void)addModel:(AccountBookModel *)model {
    self.leftView.model = model;
}


//点击同步
- (void)syncAction {
     [self saveToBmob];
}
//点击二维码
- (void)twoCodeAction {
    
}

- (void)setModel:(AccountBookModel *)model index:(NSInteger)index{
    ModifyViewController *modifyVC = [[ModifyViewController alloc] init];
    modifyVC.model = model;
    modifyVC.index = index;
    [self presentViewController:modifyVC animated:YES completion:^{
        
        
    }];
}

- (void)exchangeBackground:(NSString *)background name:(NSString *)name{
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT)];
    _topView.backgroundColor = [UIColor blackColor];
    [self.mainView.topMiddleButton setTitle:name forState:UIControlStateNormal];
    _topView.alpha = 0;
    [self.view addSubview:_topView];
    self.mainView.topImageView.image = [UIImage imageNamed:background];
    
    [self method];
    
    
    
}
- (void)method {
    [UIView animateWithDuration:0.45 animations:^{
        
        _headView.frame = CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT);
        self.backgroundScrollView.contentSize = CGSizeMake(MAIN_WIDTH * 2, MAIN_HEIGHT);
        [_sliderView removeFromSuperview];
    } completion:^(BOOL finished) {
        
        
    }];
    // [_topView removeFromSuperview];
}

- (void)setMainScrollViewScrollEnabled:(BOOL)isEnabled {
    self.backgroundScrollView.scrollEnabled = isEnabled;
}

- (void)jumpToRightDetailViewWithModel:(ChartModel *)model {
    RightDetailViewController *detailVC = [[RightDetailViewController alloc] init];
    detailVC.chartModel = model;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)saveToBmob {
    BmobUser *bUser = [BmobUser getCurrentObject];
    if (bUser) {
        //进行操作\
        
        
        
        
        
        BmobQuery   *bquery = [BmobQuery queryWithClassName:@"AccountBook"];
        //查找GameScore表的数据
        [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            for (BmobObject *obj in array) {
                
                NSLog(@"%@", [obj objectForKey:@"name"]);
                
                [obj deleteInBackground];
                
            }
        }];
        
        
        
        
        RLMResults *result = [RealmTool getCurrentAccountFromUserDefaults];
        DayBook *currentDayBook = [result firstObject];
        
        RLMResults *accountBooks = (RLMResults *)currentDayBook.bookContent;
        
//        RLMResults *accountBooks = [AccountBook allObjects];
        
        for (NSInteger i = 0; i < accountBooks.count; i++) {
            BmobObject  *accountBookInBmob = [BmobObject objectWithClassName:@"AccountBook"];
            Account *accountBook = accountBooks[i];
            [accountBookInBmob setObject:accountBook.type forKey:@"type"];
            
            [accountBookInBmob setObject:accountBook.name forKey:@"name"];
            
            [accountBookInBmob setObject:accountBook.money forKey:@"money"];
            
            [accountBookInBmob setObject:accountBook.income forKey:@"income"];
            
            [accountBookInBmob setObject:accountBook.picName forKey:@"picName"];
            
            [accountBookInBmob setObject:accountBook.time forKey:@"time"];
            
            [accountBookInBmob setObject:accountBook.remarks forKey:@"remarks"];
            
            [accountBookInBmob setObject:accountBook.imageData forKey:@"imageData"];
            
            [accountBookInBmob setObject:bUser.objectId forKey:@"userId"];
            
            //异步保存到服务器
            [accountBookInBmob saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if (isSuccessful) {
                    //创建成功后会返回objectId，updatedAt，createdAt等信息
                    //创建对象成功，打印对象值
                    NSLog(@"%@",accountBookInBmob);
                } else if (error){
                    //发生错误后的动作
                    NSLog(@"%@",error);
                } else {
                    NSLog(@"Unknow error");
                }
            }];
        }
        
        
        
    }else{
        //对象为空时，可打开用户注册界面
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        [self presentViewController:loginVC animated:YES completion:^{
            
            
        }];
    }
    
}

- (void)exchangeAccountBook:(NSNotification *)notification {
    [self createData];
    self.mainView.payAndIncomeView.incomeLabel.text = [RealmTool incomeStringFromCurrentAccountFromUserDefaults];
    self.mainView.payAndIncomeView.payLabel.text = [RealmTool payStringFromCurrentAccountFromUserDefaults];
}

@end
